package edu.uct.tamnd.viettourism.catlist;

import java.io.IOException;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import edu.uct.tamnd.viettourism.R;
import edu.uct.tamnd.viettourism.helper.DatabaseHelper;
import edu.uct.tamnd.viettourism.places.PlacesList;

public class CatList extends ListActivity {

	private DatabaseHelper dbOpenHelper ;
		
	private ArrayList<CatItem> catItems;
	private CatItemArrayAdapter adapter;
	DatabaseHelper mHelper;

	private int cityID;
	private String Name = "";
	
    private static final String TAG = "catList";
    
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.cat_list);
		
		Bundle bundle = getIntent().getExtras();
		
		cityID = bundle.getInt("cityID");
		Log.d(TAG, "Nhan cityID = " + cityID);
		
		Name = bundle.getString("cityName");
		Log.d(TAG, "Nhan cityName = " + Name);
		
		openDatabase();
		loadInfor();
		
	}
	
	
	private void loadInfor() {
		// TODO Auto-generated method stub
		catItems = new ArrayList<CatItem>();
		catItems = DatabaseHelper.readCategory(cityID);
		adapter = new CatItemArrayAdapter(CatList.this, R.layout.cat_row_item, catItems);
		setListAdapter(adapter);
		
//		cursor = mHelper.readCityName(cityID);
//		if (cursor.moveToFirst()) {
//			do {
//				Name = cursor.getString(cursor.getColumnIndex(TableNameCity.COLUMN_NAME));
//				
//			} while (cursor.moveToNext());
//			Log.d(TAG, "Name = " +Name);
//		}
		setTitle(Name);
	}


	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Bundle bundle = new Bundle();
		Intent intent = new Intent(CatList.this, PlacesList.class);
		bundle.putInt("cityID", cityID);
		bundle.putInt("catID", catItems.get(position).getId());

		Log.d(TAG, "Gui cityID = " + cityID);
		Log.d(TAG, "Gui catID = " + catItems.get(position).getId());
		intent.putExtras(bundle);
		startActivity(intent);
	}
	
	
	private void openDatabase(){
		dbOpenHelper = new DatabaseHelper(this);
		try {
			dbOpenHelper.createDatabase();
			Log.d(TAG, "Đã gọi hàm create");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d("CityList", e.getMessage());
			Toast.makeText(this, "Lỗi db", Toast.LENGTH_LONG).show();
		}
	}


	
}
